package org.log4jconfig.xml.editor.contentassist.attribute;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;

import org.eclipse.jdt.core.IJavaProject;
import org.eclipse.jdt.core.IType;
import org.eclipse.jdt.ui.ISharedImages;
import org.eclipse.wst.sse.core.utils.StringUtils;
import org.eclipse.wst.xml.core.internal.document.AttrImpl;
import org.eclipse.wst.xml.ui.internal.contentassist.ContentAssistRequest;
import org.log4jconfig.xml.editor.utils.JdtUtils;

@SuppressWarnings("restriction")
public class ParamNameContentAssistComputer extends AbstractContentAssistComputer {

	public void addAttributeValueProposals(IJavaProject javaProject, ContentAssistRequest contentAssistRequest,
			String attributeCurrentValue, String attributeMatchValue) throws Exception {
		String parentNodeName = contentAssistRequest.getNode().getParentNode().getNodeName();
		String className = ((AttrImpl) contentAssistRequest.getNode().getParentNode().getAttributes().getNamedItem(
				"class")).getValueRegionText();
		className = StringUtils.replace(className, "\"", "");
		// retrieve type given its qualified name
		IType type = javaProject.findType(className);
		Map<String, String> proposals = JdtUtils.getMethodsWithJavadocFromType(type);

		// add all items
		List<String> values = new ArrayList<String>(proposals.keySet());
		Collections.sort(values);
		for (String proposal : values) {
			if (filter(parentNodeName, proposal)) {
				super.addCompletionProposal(contentAssistRequest, proposal, proposals.get(proposal),
						attributeCurrentValue, attributeMatchValue, ISharedImages.IMG_FIELD_PUBLIC);
			}
		}
	}

	/**
	 * Until I find a better way to exclude automatically some given parameter
	 * values, we need to remove them given the parent node and the actual DTD.
	 * 
	 * @param element
	 * @param value
	 * @return
	 */
	private boolean filter(String element, String value) {
		if ("appender".equalsIgnoreCase(element)) {
			if ("name".equalsIgnoreCase(value) || "layout".equalsIgnoreCase(value)) {
				return false;
			}
		}
		return true;
	}

}
